/**
 * $Revision$
 * $Date$
 *
 * This file is part of the Solveur repository software.
 * Copyright (C) 2012 Solveur developer team
 * See http://code.google.com/p/solveur/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 **/

package gougeon.android.solveur;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MonThread implements Runnable {

	private int min_size;
	private int max_size;
	private String analyse_chaine;
	private Activity activity;
	private Handler handler;
	private Spinner mon_spinner1;
	private Spinner mon_spinner2;

	public MonThread(Activity activity, Handler handler, String analyse_chaine) {
		this.activity = activity;
		this.handler = handler;
		this.analyse_chaine = analyse_chaine;
		mon_spinner1 = (Spinner) activity.findViewById(R.id.spinner1);
		mon_spinner2 = (Spinner) activity.findViewById(R.id.spinner2);

		this.min_size = Integer.parseInt((String) mon_spinner1.getSelectedItem());
		this.max_size = Integer.parseInt((String) mon_spinner2.getSelectedItem());
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public void run() 
	{

		WebView wv = (WebView) activity.findViewById(R.id.webView1);
		int word_size;

		InputMethodManager mgr = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		final EditText mon_edittext = (EditText) activity.findViewById(R.id.input_text);
		// only will trigger it if no physical keyboard is open
		// TODO : fixme !! ça marche pas pour cacher le clavier :(
		mgr.showSoftInput(mon_edittext, InputMethodManager.HIDE_IMPLICIT_ONLY);
		
		Chaine mon_test=new Chaine(analyse_chaine);
		String data="<html><head>" +
				SolveurActivity.css_string +
				"</head><body>"+
				"Vous avez saisi : \""+analyse_chaine+
				"\" ("+analyse_chaine.length()+" lettres)<br/><br/>";

		wv.loadDataWithBaseURL("fake://not/needed", "<html><head></head><body>Patientez ...</body></html>", SolveurActivity.mimeType, SolveurActivity.encoding, "");

		Message msgA = new Message();
		msgA.arg1=max_size-min_size+1;
		msgA.what=101;
		handler.sendMessage(msgA);

		try
		{
			for (word_size=0; word_size<=8; word_size++)
			{
				if ((Mots.getMotsDeNLettresLoaded(word_size)==0) && ((min_size<=word_size) && (max_size>=word_size)))
				{
					handler.sendEmptyMessage(102);
					//Log.d("solveur : ", "Loading "+word_size+".csv");
					Mots.loadFile(activity.getAssets().open(""+word_size+".csv"), word_size);
				}
			}
		}  
		catch (IOException e)  
		{  
			//display an error toast message  
			Toast toast = Toast.makeText(activity, "File: not found!", Toast.LENGTH_LONG);  
			toast.show();
			//Log.d("solveur : ", "failed to open file" + e.getMessage());
		}

		handler.sendEmptyMessage(103);

		//Toast.makeText(SolveurActivity.this, analyse_chaine, Toast.LENGTH_SHORT).show();
		//Log.d("solveur", "Startup \""+analyse_chaine+"\" "+mon_test.getChaine_id());

		final Map<Integer,MotScore> liste_de_mots_trouves = new HashMap<Integer,MotScore>();

		int current_key[]={0,0};
		current_key[0]=0;
		current_key[1]=0;

		mon_test.analyse(	liste_de_mots_trouves,
							current_key,
							handler,
							Integer.parseInt((String) mon_spinner1.getSelectedItem()),
							Integer.parseInt((String) mon_spinner2.getSelectedItem()));

		handler.sendEmptyMessage(93);

		int total_found=liste_de_mots_trouves.size();
		data+=total_found+" résultats.<br/><br/>";
		
		if (total_found>0)
		{
			Message msg = new Message();
			msg.arg1=total_found;
			msg.what=1;
			handler.sendMessage(msg);
			int sortedListIdx;
			List<MotScore> sortedResult = new ArrayList<MotScore>(liste_de_mots_trouves.values());
			Collections.sort(sortedResult);
			int curr_word_size=Integer.parseInt((String) mon_spinner2.getSelectedItem());

			int counter_per_size=0;
			int COUNTER_LIMIT=200;

			String liste_de_mots_complets="";


			int curr_fullword=sortedResult.get(0).getFullWord();
			Log.d("solveur","total1="+total_found+" total2="+sortedResult.size());
			MotScore curr_mot_score=null;
			for (	sortedListIdx=0;
					sortedListIdx<=sortedResult.size();
					sortedListIdx++)
			{

				if (sortedListIdx<sortedResult.size())
				{
					curr_mot_score = sortedResult.get(sortedListIdx);
				}
				else
				{
					curr_mot_score = null;
				}
				if (	( sortedListIdx == sortedResult.size() )
						||	( (curr_mot_score!=null) && (curr_mot_score.getMot().length() != curr_word_size ) ) )
				{

					// Switching to other size .. finalize previous one...
					if (counter_per_size!=0)
					{
						data+=	"Mots de "+
								curr_word_size+
								" lettres (";
						if (counter_per_size<=COUNTER_LIMIT)
						{
							data+=counter_per_size;
						}
						else
						{
							data+=COUNTER_LIMIT+"/"+counter_per_size;
						}
						data+=	") :<br/><br/>"+
								liste_de_mots_complets.substring(0, liste_de_mots_complets.length()-2)+
								"<br/><br/>";
					}
					counter_per_size=0;
					liste_de_mots_complets="";
					if (curr_mot_score!=null)
					{
						curr_word_size=curr_mot_score.getMot().length();
						curr_fullword=curr_mot_score.getFullWord();
					}
					else
					{
						break;
					}
				}
				counter_per_size++;

				Message msg2 = new Message();
				msg2.arg1=sortedListIdx;
				msg2.what=3;
				handler.sendMessage(msg2);

				if (counter_per_size<COUNTER_LIMIT)
				{
					if (curr_fullword!=curr_mot_score.getFullWord())
					{
						liste_de_mots_complets=liste_de_mots_complets.substring(0, liste_de_mots_complets.length()-2);
						liste_de_mots_complets+="<br/>";
						curr_fullword=curr_mot_score.getFullWord();
					}
					sortedResult.get(sortedListIdx).setDecoration();
					liste_de_mots_complets+=	""+
												sortedResult.get(sortedListIdx).getDecoration();
				}
			}
		}
		//data+="<br/><br/>";
/*		for (	word_size=Integer.parseInt((String) mon_spinner2.getSelectedItem());
				word_size>=Integer.parseInt((String) mon_spinner1.getSelectedItem());
				word_size--)
		{
			String 	curr_mot_decorated_and_linked_old="",
					liste_mots_with_board_letter_old="",
					liste_mots_with_blank_tiles_old="",
					liste_de_mots_complets_old="";
			int num_a=0,num_b=0,num_c=0;
			counter=0;
			data=data+"Mots de "+word_size+" lettres";
			for (idx_mot=0; idx_mot<total_found; idx_mot++)
			{
				if (counter==200)
				{
					// Stop at 200 words per size for now ... 
					break;
				}

				if (liste_de_mots_trouves.containsKey(idx_mot))
				{
					//String curr_mot = liste_de_mots_trouves.get(idx_mot);
					MotScore curr_mot_obj = liste_de_mots_trouves.get(idx_mot);
					String curr_mot = curr_mot_obj.getMot();

					if(curr_mot.length()==word_size)
					{
						toto++;
						counter++;
						int allez=0;

						if (toto%10==0)
						{
							Message msg2 = new Message();
							msg2.arg1=toto;
							msg2.what=3;
							handler.sendMessage(msg2);
						}

						String lower_case=curr_mot.toLowerCase();
						String nice_mot = curr_mot.substring(0,1)+lower_case.substring(1,lower_case.length());

						// Reformat curr_mot with decoration ...
						int jdx;
						String decorated_mot="";
						String blob = analyse_chaine;

						for (jdx=0; jdx<curr_mot.length() ;jdx++)
						{
							// Enlever les accents pour matcher a l'entrée utilisateur... android 2.3.3 needed ... think about doing another way
							String curr_char=""+curr_mot.charAt(jdx);
							String normalized = Normalizer.normalize(curr_char, Normalizer.Form.NFD);
							String joli_char=normalized.replaceAll("[^\\p{ASCII}]", "");

							//int whatchar=blob.indexOf(curr_mot.charAt(jdx));
							int whatchar=blob.indexOf(joli_char.charAt(0));
							String blob2="";
							//Log.d("solveur DDD22","HOHOHO \""+ blob+"\"/\""+curr_mot+"\" "+jdx + " "+ whatchar);

							if (whatchar==-1)
							{
								// char not in the list, check if there was a blank tile
								int whatchar2=blob.indexOf(' ');
								//Log.d("solveur CCC22","HOHOHO \""+ blob+"\"/\""+curr_mot+"\" "+jdx+" "+whatchar2);
								if (whatchar2==-1)
								{
									// this char is likely to be board one...
									decorated_mot+=("<span>"+curr_char+"</span>");
									//Log.d("solveur EEE22","HOHOHO \""+ blob+"\"/\""+curr_mot+"\" "+jdx+" "+whatchar2);
									allez|=1;
								}
								else
								{
									blob2=blob.substring(0,whatchar2)+blob.substring(whatchar2+1,blob.length());
									blob = blob2;       	        	    		
									decorated_mot+=("<span><span>"+curr_char+"</span></span>");
									//Log.d("solveur AAA22","HOHOHO \""+ blob+"\"/\""+curr_mot+"\" "+jdx+" "+whatchar);
									allez|=2;
								}
							}
							else
							{
								// remove this char from blob and go on
								blob2=blob.substring(0,whatchar)+blob.substring(whatchar+1,blob.length());
								blob = blob2;
								decorated_mot+=curr_char;

								allez|=4;
								//Log.d("solveur BBB22","HOHOHO \""+ blob+"\"/\""+curr_mot+"\" "+jdx+" "+whatchar);
							}
						}
						curr_mot_decorated_and_linked_old="<a href=\"http://fr.wikipedia.org/wiki/"+nice_mot+ "\"  class=\"example\">"+decorated_mot+"</a> ("+curr_mot_obj.getScore()+") - ";
						if ((allez&1)==1)
						{
							num_c++;
							liste_mots_with_board_letter_old+=curr_mot_decorated_and_linked_old;
						}
						else if ((allez&2)==2)
						{
							num_b++;
							liste_mots_with_blank_tiles_old+=curr_mot_decorated_and_linked_old;
						}
						else
						{
							num_a++;
							liste_de_mots_complets_old+=curr_mot_decorated_and_linked_old;
						}
						//Log.d("solveur",""+curr_mot+"  allez="+allez+" / "+num_a+" "+num_b+" "+num_c);
						//Log.d("solveur",data2);

						// Remove this word from list to speed up next lookups...
						//liste_de_mots_trouves.remove(idx_mot);
						liste_de_mots_trouves.remove(idx_mot);
					}
				}
			}

			data=data+" ("+counter+") :<br/>";
			if (num_a!=0)
			{
				data+=liste_de_mots_complets_old+"<br/>";
			}
			if (num_b!=0)
			{
				data+=liste_mots_with_blank_tiles_old+"<br/>";
			}
			if (num_c!=0)
			{
				data+=liste_mots_with_board_letter_old+"<br/>";
			}
			data+="<br>";
			//wv.loadDataWithBaseURL("fake://not/needed", data+"</body></html>", mimeType, encoding, "");
		}
*/
		data+="</body></html>";

		handler.sendEmptyMessage(4);

		//Log.i("solveur","DATA="+data);
		wv.loadDataWithBaseURL("fake://not/needed", data, SolveurActivity.mimeType, SolveurActivity.encoding, "");
	}

}
